package com.acxiom.bsh.controller;

import java.net.URLEncoder;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.acxiom.bsh.constants.CommonConstant;
import com.acxiom.bsh.constants.ThreadLocalContextHolder;
import com.acxiom.bsh.entity.Customer;
import com.acxiom.bsh.logger.LoggerManager;
import com.acxiom.bsh.pojo.ApiMeta;
import com.acxiom.bsh.response.ApiResponse;
import com.acxiom.bsh.service.ApiService;
import com.acxiom.bsh.taobao.sdk.TbAuthorize;
import com.acxiom.bsh.util.DateUtils;
import com.alibaba.fastjson.JSONObject;

/**
 * 
 * @Description: 互动应用入口
 * @author jerche
 *
 * @updateUser
 * @updateDate
 */
@Controller
public class HomeController {

	private static final String redirect = "redirect:";
	private static final String STORE_ID = "storeId";
	private static final String SELLER_ID = "sellerId";
	private static final String REDIRECT_URL = "redirecturl";
	private static final String TAOBAO_NICK = "taobao_user_nick";
	@Autowired
	private ApiService apiService;
	/**
	 * 淘宝聚石塔 ews BSH 域名
	 */
	@Value("${ewsDomain}")
	private String ewsDomain;

	/**
	 * 淘宝开放平台TOP 百川无线应用 appkey
	 */
	@Value("${ewsAppKey}")
	private String ewsAppKey;

	/**
	 * 淘宝开放平台TOP 百川无线应用 appSecret
	 */
	@Value("${ewsAppSecret}")
	private String ewsAppSecret;

	/**
	 * 淘宝开放平台TOP 商家后台系统应用授权的sessionkey
	 */
	@Value("${ewsSessionKey}")
	private String topSessionKey;

	/**
	 * 淘宝开放平台TOP 网关路由地址http://gw.api.taobao.com/router/rest
	 */
	@Value("${topServiceUrl}")
	private String topServiceUrl;
	/**
	 * 淘宝商家id
	 */
	@Value("${tmall.default.sellerId}")
	private String defaultSellerId;
	/**
	 * 淘宝商家店铺Id
	 */
	@Value("${tmall.default.shopId}")
	private String defaultShopId;

	/**
	 * 关注功能入口
	 * 
	 * @Title: attention 关注
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @param sellerId
	 *            淘宝商家Id
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @return
	 */
	@RequestMapping(value = "/attention/{storeId}")
	public String attention(@PathVariable(name = "storeId") String storeId, @RequestParam(value = "sellerId", required = false) String sellerId, Model model, HttpSession session) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/attention/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}
		String redirecturl = redirectUrl(storeId);
		if (sellerId == null || "".equals(sellerId.trim())) {
			sellerId = defaultSellerId;
		}
		model.addAttribute(SELLER_ID, sellerId);
		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "attention";
	}

	/**
	 * 
	 * 会员中心签到入口
	 * 
	 * @Title: checkin 会员中心签到
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @return
	 */
	@RequestMapping(value = "/checkin/{storeId}")
	public String checkin(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/checkin/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}
		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "checkin";
	}

	/**
	 * 
	 * 会员中心收藏入口
	 * 
	 * @Title: checkin 会员中心收藏
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @param shopId
	 *            淘宝商家店铺id
	 * @return
	 */
	@RequestMapping(value = "/collection/{storeId}")
	public String collection(@PathVariable(name = "storeId") String storeId, @RequestParam(value = "shopId", required = false) String shopId, Model model, HttpSession session) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/collection/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}
		if (shopId == null || "".equals(shopId.trim())) {
			shopId = defaultShopId;
		}
		model.addAttribute("shopId", shopId);
		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "collection";
	}

	/**
	 * 
	 * 抽奖记录入口
	 * 
	 * @Title: checkin 抽奖记录
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @return
	 */
	@RequestMapping(value = "/prize/{storeId}")
	public String prize(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/prize/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}
		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "prize";
	}

	/**
	 * 
	 * 售后入口
	 * 
	 * @Title: repair 售后
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @return
	 */
	@RequestMapping(value = "/repair/{storeId}")
	public String repair(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/repair/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}
		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "repair";
	}

	/**
	 * 
	 * 会员中心个人信息入口
	 * 
	 * @Title: profile 会员中心个人信息
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @param tabIndex
	 *            用作跳转tab页面
	 * @return
	 */
	@RequestMapping(value = "/profile/{storeId}")
	public String profile(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId, @RequestParam(value = "tabIndex", required = false) Integer tabIndex) {
		try {

			Object taobaoUserNick = session.getAttribute(TAOBAO_NICK);
			if (null == taobaoUserNick) {
				String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/profile/" + storeId), "200");
				return redirect + redirectUrl;
			}

			String originNickName = taobaoUserNick.toString();
			String backurl = getBackUrl(storeId);
			String redirecturl = redirectUrl(storeId);
			if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
				return redirect + backurl;
			}
			if (originNickName.contains("\\")) {
				originNickName.replaceAll("\\", "\\\\");
			}

			model.addAttribute("taobao_nick", originNickName);
			int idx = -1;
			if (tabIndex != null) {
				idx = tabIndex;
			}
			model.addAttribute("tabIndex", idx);
			session.setAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE, originNickName);

			model.addAttribute(STORE_ID, storeId);
			model.addAttribute(REDIRECT_URL, redirecturl);
		} catch (Exception e) {
			LoggerManager.getErrorLogger().error("get profile error: " + e.getMessage());
		}
		return "profile";
	}

	/**
	 * 
	 * 抽奖大转盘入口
	 * 
	 * @Title: truntable 抽奖大转盘
	 * @param model
	 * @param session
	 *            存储淘宝用户信息会话
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @return
	 */
	@RequestMapping(value = "/turntable/{storeId}")
	public String truntable(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {
		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/turntable/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick), storeId)) {
			return redirect + backurl;
		}

		if (judgeInDouble11()) {
			model.addAttribute(STORE_ID, storeId);
			model.addAttribute(REDIRECT_URL, redirecturl);
			return "double11draw";
		}

		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "turntable";
	}

	/**
	 * double11 用户红包抽奖测试接口入口(已禁用)
	 * 
	 * @Title: luckydraw
	 * @param model
	 * @param session
	 * @param storeId
	 * @return
	 */
	@RequestMapping(value = "/acxiom/double11/lucky/draw/987453656e3/{storeId}")
	public String luckydraw(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {

		Object taobaoUserNick = session.getAttribute(CommonConstant.TAOBAO_NICK_ATTRIBUTE);
		if (null == taobaoUserNick) {
			String redirectUrl = TbAuthorize.buildAuthorizeUrl(ewsAppKey, ewsDomain.concat("/tb/authorize/turntable/" + storeId), "200");
			return redirect + redirectUrl;
		}
		String backurl = getBackUrl(storeId);
		String redirecturl = redirectUrl(storeId);
		if (!validateCustomerIsBinded(String.valueOf(taobaoUserNick),storeId)) {
			return redirect + backurl;
		}

		model.addAttribute(STORE_ID, storeId);
		model.addAttribute(REDIRECT_URL, redirecturl);
		return "turntable";
	}

	/**
	 * 验证用户是否绑定
	 * 
	 * @Title: validateCustomerIsBinded
	 * @param mixnick
	 *            密文nick
	 * @return
	 */
	public boolean validateCustomerIsBinded(String mixnick, String storeId) {

		try {
			if (StringUtils.isNotBlank(storeId)) {
				String sellerName = null;
				if ("1".equals(storeId)) {
					sellerName = "西门子家电官方旗舰店";
				} else if ("2".equals(storeId)) {
					sellerName = "西门子家电厨卫旗舰店";
				} else if ("3".equals(storeId)) {
					sellerName = "博西华电器专营店";
				}
				ThreadLocalContextHolder.get().setValue(URLEncoder.encode(sellerName, "UTF-8"));
			}
			String path = String.format("member?iSN=%d&mix_taobaoId=%s", System.currentTimeMillis(), mixnick);
			ApiResponse response = apiService.get(path);
			Object object = response.getData();
			ApiMeta meta = response.getMeta();

			Customer customer = (Customer) JSONObject.parseObject(JSONObject.toJSONString(object), Customer.class);
			if (meta != null && meta.isSuccess()) {
				if (customer != null) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	@RequestMapping(value = "/load/index/{storeId}")
	public String loadIndex(Model model, HttpSession session, @PathVariable(name = "storeId") String storeId) {
		String redirecturl = backUrl(storeId);
		return redirect + redirecturl;
	}

	public String backUrl(String storeId) {
		String url = "";
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		String user_agent = request.getHeader("user-agent");
		if (TbAuthorize.isMobileDevice(user_agent)) {
			url = "https://siemens-home.tmall.com";
		} else {
			url = "https://siemens-home.tmall.com";
		}
		return url;
	}

	/**
	 * 判断用户是从哪家店铺访问并返回到相关店铺
	 * 
	 * @Title: redirectUrl
	 * @param storeId
	 *            店铺标识(由商家或ISV自定义)
	 * @return
	 */
	public String redirectUrl(String storeId) {
		String url = "";
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest request = sra.getRequest();
		String user_agent = request.getHeader("user-agent");

		if ("1".equals(storeId)) {
			if (TbAuthorize.isMobileDevice(user_agent)) {
				url = "https://shop.m.taobao.com/shop/activity_page.htm?wh_weex=true&pathInfo=shop/activity&userId=859230932&shopId=71236848&pageId=116926419";
			} else {
				url = "http://siemens-home.tmall.com/p/rd104153.htm";
			}
		} else if ("2".equals(storeId)) {

			if (TbAuthorize.isMobileDevice(user_agent)) {
				url = "https://shop.m.taobao.com/shop/activity_page.htm?wh_weex=true&pathInfo=shop/activity&userId=3039860834&shopId=301821232&pageId=118788240";
			} else {
				url = "http://siemens.tmall.com/p/rd167834.htm";
			}

		} else if ("3".equals(storeId)) {
			if (TbAuthorize.isMobileDevice(user_agent)) {
				url = "https://shop.m.taobao.com/shop/activity_page.htm?wh_weex=true&pathInfo=shop/activity&userId=2273736058&shopId=114149468&pageId=118554325";
			} else {
				url = "http://bxhdq.tmall.com/p/rd905707.htm";
			}
		}
		return url;
	}

	public String getBackUrl(String storeId) {
		String url = "";
		if ("1".equals(storeId)) {
			url = "https://bvip.tmall.com/crm/member.htm?id=859230932";
		} else if ("2".equals(storeId)) {
			url = "https://bvip.m.tmall.com/crm/member.htm?id=3039860834";
		} else if ("3".equals(storeId)) {
			url = "https://bvip.tmall.com/crm/member.htm?id=2273736058";
		}
		return url;
	}

	/**
	 * 判断是否在双十一活动时间
	 * 
	 * @Title: judgeInDouble11
	 * @return
	 */
	public boolean judgeInDouble11() {
		Date date = new Date();
		long currentTime = date.getTime();
		long start_11 = DateUtils.stringToDate("2017-12-05 22:00:00").getTime();
		long end_11 = DateUtils.stringToDate("2017-12-12 23:59:59").getTime();
		return (currentTime >= start_11 && currentTime < end_11);
	}

}
